package com.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebFilter(urlPatterns = { "/*" }, initParams = {
		@WebInitParam(name = "sessionKey", value = "User"),
		@WebInitParam(name = "redirectUrl", value = "/"),
		@WebInitParam(name = "notCheckUrlList", value = "/index.jsp;/UserController") })
public class SecurityFilter implements Filter {
	private String redirectUrl = null;
	private List notCheckUrlList = new ArrayList();
	private String sessionKey = null;

	public SecurityFilter() {
		// TODO Auto-generated constructor stub
	}

	public void destroy() {
		System.out.println("登录验证过滤器销毁!");
		notCheckUrlList.clear();
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		HttpSession session = req.getSession();

		if (sessionKey == null) {
			chain.doFilter(req, resp);
			return ;
		}
		if ((!checkRequestURIIntNotFilterList(req))
				&& session.getAttribute(sessionKey) == null) {
			resp.sendRedirect(req.getContextPath() + redirectUrl);
			return;
		}
		chain.doFilter(request, response);
	}

	public void init(FilterConfig fConfig) throws ServletException {
		
		System.out.println("登录验证过滤器初始化!");
		
		redirectUrl = fConfig.getInitParameter("redirectUrl");
		sessionKey = fConfig.getInitParameter("sessionKey");

		String notCheckUrl = fConfig.getInitParameter("notCheckUrlList");

		if (notCheckUrl != null) {
			StringTokenizer str = new StringTokenizer(notCheckUrl, ";");
			notCheckUrlList.clear();
			while (str.hasMoreTokens()) {
				notCheckUrlList.add(str.nextToken());
			}
		}
	}

	private boolean checkRequestURIIntNotFilterList(HttpServletRequest request) {
		String uri = request.getServletPath()
				+ (request.getPathInfo() == null ? "" : request.getPathInfo());
		return notCheckUrlList.contains(uri);
	}

}
